.PHONY : all clean

CC := gcc
MKDIR := mkdir
RM := rm -rf

#already exist dir
DIR_INCLUDES := include
DIR_SRC := communicate

#dir that need to be created 
DIR_BIN := bin
DIR_OBJ := obj
DIR_DEP := dep

LIBS = -pthread

ifeq ("$(DEBUG)","y")
CFLAGS := -g
endif

INCLUDES := $(foreach dir,$(DIR_INCLUDES),-I$(dir))
DIRS := $(DIR_BIN) $(DIR_OBJ) $(DIR_DEP)

SRCS := $(wildcard $(DIR_SRC)/*.c)
OBJS := $(SRCS:.c=.o)
OBJS := $(subst $(DIR_SRC),$(DIR_OBJ),$(OBJS)) 
DEPS := $(SRCS:.c=.d)
DEPS := $(subst $(DIR_SRC),$(DIR_DEP),$(DEPS)) 

EXE := server
EXE := $(addprefix $(DIR_BIN)/,$(EXE))

all : $(DIR_OBJ) $(DIR_BIN) $(EXE)

ifeq ("$(MAKECMDGOALS)","all")
-include $(DEPS)
endif

ifeq ("$(MAKECMDGOALS)","")
-include $(DEPS)
endif

$(EXE) : $(OBJS)
	$(CC) $(CFLGAS) $(LIBS) -o $@ $^
	echo "Success! Target => $@"

$(DIR_OBJ)/%.o : $(DIR_SRC)/%.c
	$(CC) $(CFLAGS) $(INCLUDES) -o $@ -c $(filter $(DIR_SRC)/%.c,$^)

$(DIRS) :
	$(MKDIR) $@

ifeq ("$(wildcard $(DIR_DEP))","")
$(DIR_DEP)/%.d : $(DIR_DEP) $(DIR_SRC)/%.c
else
$(DIR_DEP)/%.d : $(DIR_SRC)/%.c
endif
	@echo "Creating $@..."
	@set -e;\
	$(CC) -MM $(INCLUDES) $(filter %.c,$^) | sed 's,\(.*\)\.o[ :]*,$(DIR_OBJ)/\1.o $@: ,g' > $@

clean:
	$(RM) $(DIRS)
